package func;

## This file is part of the Simplemail project.
#  Copyright (c) 2008 the Simplemail Team (see authors).
# 
#  For the full copyright and license information, please view the COPYING
#  file that was distributed with this source code. You can also view the
#  COPYING file online at http://unixforum.org.ua/misc/COPYING.txt
# 
#  @copyright  (c) the authors
#  @author     Dmitriy Shilenko <rtyug@ukr.net>
#  @license    GPLv2 http://unixforum.org.ua/misc/COPYING.txt
#  @package    Panel Mailbox
#  @version    $Id: $

use strict;
use CGI::Carp qw(fatalsToBrowser);
use DBI;

#use HTML::Template;
#use POSIX qw(ceil floor);

sub new {

    my ( $class, %common ) = @_;
    my $self = {
        se      => undef,
        cookie  => undef,
        env     => undef,
        session => undef,
        he      => undef,
        p       => undef,
        query   => undef
    };

    $self->{'se'}      = $common{'se'}      if $common{'se'};
    $self->{'session'} = $common{'session'} if $common{'session'};
    $self->{'he'}      = $common{'he'}      if $common{'he'};
    $self->{p}       = $common{p}       if $common{p};
    $self->{query}   = $common{query}   if $common{query};

    # $self->{'passwd'} = $common{'passwd'} if $common{'passwd'};

    if ( $common{passwd} ) {
        $self = &md5crypt( $self, $common{'passwd'} );
    }

    bless $self, $class;

    return $self;
}

sub dbi_connect {
    my $self = shift;

    $self->{dbh} = DBI->connect(
	$self->{se}->{dsn},
        $self->{se}->{db_user},
        $self->{se}->{db_pass},
        { RaiseError => 1, 
         PrintError => 1 }
    ) || die $DBI::errstr;


    return $self;
    
}

sub md5crypt {
    my ( $self, $passwd ) = @_;
    my $salt;

    my @rnd_txt = ( '.', '/', 0 .. 9, 'A' .. 'Z', 'a' .. 'z' );

    srand;

    for ( 0 .. 7 ) {
        my $s = rand(@rnd_txt);
        $salt .= $rnd_txt[$s];
    }

    my $salt = "\$1\$$salt\$";

    return crypt( $passwd, $salt );

}

sub sent_email {

    my $self     = shift;
    my @smtp_out = ();

    use IO::Socket;
    my $socket = IO::Socket::INET->new( PeerAddr => 'localhost:smtp(25)' )
      or die "ERROR: $!";
    my $answer_data;

    sysread $socket, $answer_data, 255;
    $smtp_out[0] = "1: $answer_data";

    syswrite $socket, "helo $self->{'se'}->{'smtp_server'}\r\n";
    sysread $socket, $answer_data, 255;
    $smtp_out[1] = "2: $answer_data";

    syswrite $socket, "mail from:<$self->{'se'}->{'mail_from'}>\r\n";
    sysread $socket, $answer_data, 255;
    $smtp_out[2] = "3: $answer_data";

    syswrite $socket, "rcpt to:<$self->{'p'}->{'email_smtp'}>\r\n";
    sysread $socket, $answer_data, 255;
    $smtp_out[3] = "4: $answer_data";

    syswrite $socket, "data\r\n";
    sysread $socket, $answer_data, 255;
    $smtp_out[4] = "5: $answer_data";

    syswrite $socket, "$self->{'se'}->{'text_new_mailbox'}\r\n";

    syswrite $socket, ".\r\n";
    sysread $socket, $answer_data, 255;
    $smtp_out[5] = "6: $answer_data";

    syswrite $socket, "quit\r\n";
    sysread $socket, $answer_data, 255;
    $smtp_out[7] = "7: $answer_data";

    close $socket;

    @smtp_out = map +{ answer => $_ }, @smtp_out;
    $self->{he}->{SOCKET} = \@smtp_out;

    return $self;
}

sub page_list {

    my $self = shift;

    my ( $jj, $page );

#$self->{p}->{total_pages} =  ceil ($self->{p}->{total_number}/$self->{se}->{line_from_page});
    $self->{p}->{total_pages} = sprintf( '%.f',
        $self->{p}->{total_number} / $self->{se}->{line_from_page} );

    if ( $self->{p}->{from} > $self->{p}->{total_pages} ) {
        $self->{p}->{from} = $self->{p}->{total_pages};
    }

    $jj = 0;
    if ( $self->{p}->{from} eq '' ) {
        $jj = 0;
    }

    else {
        $jj = ( $self->{p}->{from} - 1 ) * $self->{se}->{line_from_page};
    }

    my $page_number;
    my $i;
    for ( $i = 0 ; $i < $self->{p}->{total_pages} ; $i++ ) {

        $page_number++;
        last if ( $self->{p}->{total_pages} <= 1 );

        next if ( $page_number > $self->{p}->{from} + 4 );
        next if ( $page_number < $self->{p}->{from} - 4 );

        if ( $page_number > $self->{p}->{from} + 3 ) {
            $page .= << "[HTML]";
<a href="index.pl?action=postfix&postfixactive=$self->{'p'}->{'file'}&from=$self->{p}->{total_pages}$self->{p}->{url}"> |... $self->{p}->{total_pages}|</a>   
[HTML]
            next;
        }

        if ( $page_number < $self->{p}->{from} - 3 ) {
            $page .= << "[HTML]";
<a href="index.pl?action=postfix&postfixactive=$self->{p}->{file}&from=1$self->{p}->{url}"> | 1...  |</a>   
[HTML]
            next;
        }

        if ( $page_number ne $self->{p}->{from} ) {

            $page .= << "[HTML]";
 <a href="index.pl?action=postfix&postfixactive=$self->{p}->{file}&from=$page_number$self->{p}->{url}"> | $page_number  |</a>   
[HTML]
        }
        else {

            $page .= << "[INFO3]";
 <a href="index.pl?action=postfix&postfixactive=$self->{p}->{file}&from=$page_number$self->{p}->{url}"> | <b> $page_number </b> |</a>   
[INFO3]

        }
    }

    $self->{he}->{page} = $page;
    $self->{p}->{jj}    = $jj;
    return $self;
}

sub insert_logsmail {
    my $self = shift;

    if (
        $self->{se}->{active_logsm} == 1
        || (   $self->{se}->{active_logsm} != 1
            && $self->{session}->{filet} eq 'error_login2' )
      )
    {

        $ENV{'REMOTE_ADDR'}          =~ /(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})/g;
        $ENV{'HTTP_X_FORWARDED_FOR'} =~ /(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})/g;

        $ENV{'REMOTE_ADDR'}          = $ENV{'REMOTE_ADDR'}          || 'empty';
        $ENV{'HTTP_X_FORWARDED_FOR'} = $ENV{'HTTP_X_FORWARDED_FOR'} || 'empty';

        $self->{session}->{user} = $self->{session}->{user} || 'empty';

        $self->{dbh}->do(
            qq{INSERT INTO log_smail
                        (action,
                         userid, 
                         created, 
                         ip,
                         forwarded) VALUES (?, ?, ?, ?, ?)},
            undef, $self->{session}->{filet}, $self->{session}->{user}, time,
            $ENV{'REMOTE_ADDR'}, $ENV{'HTTP_X_FORWARDED_FOR'}
        );
    }
    return $self;
}

sub templ_hash {
    my $self = shift;

    $self->insert_logsmail if $self->can("insert_logsmail");

    $self->{he}->{ADMIN_SEE} = 1 if ( $self->{session}->{name} eq 'Admin' );
    $self->{he}->{WELCOME}   = 1;
    $self->{he}->{USERSE}    = $self->{session}->{name};

    $self->{he}->{url} = $self->{se}->{url};

    my $template = HTML::Template->new(
        filename => $self->{se}->{dirt}
          . 'tempele-postfix-'
          . $self->{session}->{filet} . '.html',
        die_on_bad_params => 0,
        blind_cache       => $self->{se}->{blind_cache}
    );

    while ( my ( $key, $value ) = each( %{ $self->{he} } ) ) {
        $template->param( $key => $value );
    }

    if ( $self->{session}->{cookie} ) {

        print $self->{query}
          ->header( -charset => 'utf8', -cookie => $self->{session}->{cookie} );
    }
    else {
        print $self->{query}->header( -charset => 'utf8' );
    }

    #use Data::Dumper;
    #print Dumper($self->{cookie});

    print $template->output();
    return $self;
}

sub DESTROY {
    my $self = shift;

    $self->{dbh}->disconnect();
    $self->{p}  = undef;
    $self->{se} = undef;

    #$self->{session} = undef;
    #$self->{se} = undef;
    #$self = undef;
}

1;

